package com.jason.www;

import com.jason.www.pojo.User;
import com.jason.www.utils.ProtobufUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.util.Arrays;

public class ProtostuffDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user = new User();
        user.setName("如来佛祖玉皇大帝超级无敌孙悟空");
        user.setAge(11);
        user.setBirth(LocalDateTime.now());
        user.setMoney(100d);
        user.setTag(Arrays.asList("aa","bb","cc"));
        byte[] protostuffSerialize = ProtobufUtil.serialize(user);
        System.out.println("Protostuff序列化后的长度：" + protostuffSerialize.length);
        User deserialize = ProtobufUtil.unSerialize(protostuffSerialize, User.class);
        System.out.println(deserialize);
        byte[] originalSerialize = originalSerialize(user);
        System.out.println("Jdk序列化后的长度：" + originalSerialize.length);
        User originalDeserialize = originalDeserialize(originalSerialize);
        System.out.println(originalDeserialize);
    }

    private static <T> T originalDeserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        //字节码转换成对象
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream);
        T result = (T) inputStream.readObject();
        inputStream.close();
        return result;
    }

    private static <T> byte[] originalSerialize(T t) throws IOException {
        //对象转成字节码
        ByteArrayOutputStream byteArrayOutputStream = new  ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream);
        outputStream.writeObject(t);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        outputStream.close();
        return bytes;
    }
}
